import unittest, inspect, datetime, sys, os, csv,time, re, traceback
import argparse, optparse, pyodbc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import NoSuchElementException 

env_variable="qa2"  #"dev", "qa1","qa2", "stage"
base_url = "http://"



class SeleniumTestHelper(): #object
    """This class should have helper methods related to enhancing 
    Selenium's capabilities """
    
    @classmethod
    def environment_setter(cls, option):
        
        if option == 'dev':
            print "running tests for: DEV"
            import VariablesDEV_WD as config
            
        elif option == "qa1":
            print "running tests for: QA"
            import VariablesQA1_WD as config
            
        
        elif option == "qa2":
            print "running tests for: QA"
            import VariablesQA2_WD as config
            
        elif option == "stage":
            print "running tests for: STAGE"
            import VariablesSTAGE_WD as config 
            
        elif option == "prod":
            print "You are running the test in Prod. This is not allowed"
        """ locals() return everything in my namespace, but we used config """   
        return config
        
        
    @classmethod
    def exception_found(cls,e, full_exc, now, file_name, name_of_test, driver, *variables): #, driver_source):
            #print e
            error_timestamp= (now.strftime("%Y%m%d %H:%M"))
            #driver.get_screenshot_as_file('screenshot-%s.png' % now)
            driver.save_screenshot("Captures/%s_%s.png"%(file_name, name_of_test))
            driver_source = driver.page_source
            cur_url = str(driver.current_url)
            variables = (str(variables))
            print("EXCEPTION Occurred in: %s "  % name_of_test )
            #print str(e)
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]      
            print(exc_type, "filename: " + str(fname), "Line number: " +str(exc_tb.tb_lineno))

            
            try:
                # This will create a new file or **overwrite an existing file**.
                f = open("Captures/errorsource_%s_%s.html" % (file_name, name_of_test), "w")
                try:
                    f.write('<html>')
                    f.write('<b>'+'Name of Test : ' + str(name_of_test)+' '+'<br>') # Write a string to a file
                    f.write('Date and Time: ' +error_timestamp+' ' +'<br>')
                    f.write('Variables: ' + variables + '<br>')
                    f.write('URL: '+cur_url +' '+ '</b>' + '<br>'+ '<br>')
                    f.write('<b>'+'(FOR QA ONLY) Specific Exception from Selenium:' +'</b>'+full_exc +'<br>' +'<br>')
                    f.writelines(driver_source) # Write a sequence of strings to a file
                    f.write('</html>')
                finally:
                    f.close()
            except IOError:
                pass

            return error_timestamp,full_exc, "filename: " + str(fname)
            
    
            


class IWTtestHelper(unittest.TestCase):
    """ This class should have methods related specifically to IWT_AVW.py tests"""
    
    @classmethod
    def is_element_present(self,driver, how, what):
    
        try: driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    @classmethod
    def address_fill_in(self,driver, tst_user_list,row):
        now = datetime.datetime.now()
        print("typing info for: "+str(tst_user_list[row]), " time is:  ", now.strftime("%Y-%m-%d %H:%M:%S"))
        driver.find_element_by_css_selector("input#iceAddress_1_street_1").clear()
        driver.find_element_by_css_selector("input#iceAddress_1_street_1").send_keys(tst_user_list[row][1])
        #time.sleep(2)
        driver.find_element_by_css_selector("input#iceAddress_1_street_2").clear()
        driver.find_element_by_css_selector("input#iceAddress_1_street_2").send_keys(tst_user_list[row][2])
        #time.sleep(2)
        driver.find_element_by_css_selector("input#iceAddress_1_city").clear()
        driver.find_element_by_css_selector("input#iceAddress_1_city").send_keys(tst_user_list[row][3])
        time.sleep(1)
        driver.find_element_by_css_selector("input#iceAddress_1_postalCode").clear()
        driver.find_element_by_css_selector("input#iceAddress_1_postalCode").send_keys(tst_user_list[row][5])
        time.sleep(2)
        Select(driver.find_element_by_css_selector("select#iceAddress_1_state")).select_by_visible_text(tst_user_list[row][4])
        time.sleep(3)
    
    @classmethod
    def monthly_contact(self, driver,name_of_test):
        print ("Starting monthly contact")
        driver.find_element_by_css_selector("div.sg-question-title")
        
        driver.find_element_by_css_selector("#sgE-923012-1-3-10002").click()
        driver.find_element_by_css_selector("#sgE-923012-1-4-element").clear()
        driver.find_element_by_css_selector("#sgE-923012-1-4-element").send_keys("HC address is wrong")
        driver.find_element_by_css_selector("#sgE-923012-1-5-10003").click()
    
        driver.find_element_by_css_selector("#sgE-923012-1-7-10007").click()
        
        # Q4. Monthly Activities 
        driver.find_element_by_css_selector("#sgE-923012-1-9-10029").click()
        # Q5. Rate your experience
        driver.find_element_by_css_selector("#sgE-923012-1-10-10012").click()
        driver.find_element_by_css_selector("#sg_SubmitButton").click()
        print ("Finished monthly contact")
        time.sleep(3)
    
    
    
    
if __name__ == '__main__':    
    print env_variable
#
#    unittest.main()





